layui.use(['ExTree', 'DynamicForm', 'LayerAjax', 'LayerForm', 'table'], function () {
    var $ = layui.$;
    var exbase = layui.exbase;
    var table = layui.table;
    var userTable = null;
    var treeLoader = new layui.ExTree({
        id: "org_tree",
        elem: '#org_tree_id',
        url: ctxPath + "/admin/orgs/-1/tree?recursive=true",
        onlyIconControl: true,
        format: function (data) {
            data.title = data.name;
            data.spread = true;
            return data;
        },
        rightMenus: function (node) {
            if (node.data.leaf) {
                return [{
                    name: "编辑",
                    click: function (node) {
                        configUpdateButton(node);
                    }
                }, {
                    name: "删除",
                    click: function (node) {
                        configDeleteButton(node);
                    }
                }];
            } else if (node.data.parentId == -1) {
                return [{
                    name: "新增子组织",
                    click: function (node) {
                        configAddButton(node);
                    }
                }]
            } else {
                return [{
                    name: "新增子组织",
                    click: function (node) {
                        configAddButton(node);
                    }
                }, {
                    name: "编辑",
                    click: function (node) {
                        configUpdateButton(node);
                    }
                }, {
                    name: "删除",
                    click: function (node) {
                        configDeleteButton(node);
                    }
                }];
            }
        },
        click: function (node) {
            var orgId = node.data.id;
            $("#keyword_input_id").val("")
            $("#user_div_id").show()
            $("#user_tip_div_id").hide()
            userTable = layui.table.render({
                id: 'user_table_id',
                elem: '#user_table_id',
                url: ctxPath + "/admin/orgs/" + orgId + "/users/page",
                page: {
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                    , first: false //不显示首页
                    , last: false //不显示尾页
                } //开启分页
                , cols: [[ //表头
                    {checkbox: true}
                    , {field: 'number', title: '', type: 'numbers'}
                    , {field: 'id', title: 'ID', width: 80, sort: true, hide: true}
                    , {field: 'account', title: '账号'}
                    , {field: 'name', title: '用户名'}
                    , {field: 'age', title: '年龄'}
                    , {field: 'mobilePhone', title: '手机号'}
                    , {field: 'state', title: '状态', templet: '#stateTemplate'}
                ]]
                , parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.totalElements, //解析数据长度
                        "data": res.data.content //解析数据列表
                    };
                }
            })


            $("#addUser_button_id").off("click").on('click',function (){
                layer.open({
                    type: 1,
                    title: '添加用户到组织',
                    area: ['600px', '400px'],
                    shadeClose: true,
                    content: $('#addUser_div_id'),
                    success: function (layero, index) {
                        var addUserTable = table.render({
                            elem: '#add_user_table_id'
                            , id: 'add_user_table_id'
                            , url: ctxPath + '/admin/users/page?notOrgId=' + orgId
                            , page: {
                                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                                , first: false //不显示首页
                                , last: false //不显示尾页
                            } //开启分页
                            , cols: [[ //表头
                                {checkbox: true}
                                , {field: 'id', title: 'ID', width: 80, sort: true, hide: true}
                                , {field: 'account', title: '账号'}
                                , {field: 'name', title: '用户名'}
                                , {field: 'mobilePhone', title: '手机号'}
                            ]]
                            , parseData: function (res) { //res 即为原始返回的数据
                                return {
                                    "code": res.code, //解析接口状态
                                    "msg": res.msg, //解析提示文本
                                    "count": res.data.totalElements, //解析数据长度
                                    "data": res.data.content //解析数据列表
                                };
                            }
                        });
                        layui.form.on('submit(search_addUser_button_filter)', function (data) {
                            var keyword = data.field.keyword
                            addUserTable.reload({
                                where : {
                                    keyword: (keyword || '')
                                }
                            })
                            return false;
                        })
                        $("#submit_orgUser_button_id").off('click').on('click',function () {
                            var checkStatus = table.checkStatus('add_user_table_id');
                            if (checkStatus.data.length == 0) {
                                layer.alert("请选中一条数据后操作", {title: '提示'})
                                return
                            }
                            var idList = checkStatus.data.map(a => a.id)
                            $.ajax({
                                url: ctxPath + "/admin/orgs/" + orgId + "/users",
                                method: 'POST',
                                data: {userIds: idList},
                                success:function (data) {
                                    if(data.code == exbase.AJAX_SUCCESS_CODE) {
                                        layer.msg("添加用户到当前组织成功")
                                        layer.close(index)
                                        userTable.reload()
                                    } else {
                                        layer.msg(data.msg, {icon: 2})
                                    }
                                }
                            })
                        })
                    }
                })



            })

            $("#deleteUser_button_id").off("click").on('click',function (){
                var checkStatus = table.checkStatus('user_table_id');
                if (checkStatus.data.length == 0) {
                    layer.alert("请至少选中一条数据后操作", {title: '提示'})
                    return
                }

                var idList = checkStatus.data.map(a => a.id).join(",")
                var dialog = new layui.LayerAjax({
                    title: "从组织中移除选中用户",
                    url: ctxPath + "/admin/orgs/" + orgId + "/users/" + idList,
                    data: {},
                    method: "delete",
                    success: function () {
                        userTable.reload();
                    }
                })
                dialog.open()
            })


        }
    });
    treeLoader.load();

    function configAddButton(node) {
        var form = new layui.LayerForm({
            title: "创建组织",
            form: [{
                label: "名称",
                name: "name",
                type: "text"
            }, {
                label: "类型",
                name: "type",
                type: "select",
                options: [{
                    label: "公司",
                    value: 'company'
                }, {
                    label: "部门",
                    value: 'department'
                }, {
                    label: "小组",
                    value: 'team'
                }]
            }, {
                label: "排序",
                name: "ordered",
                type: "text"
            }, {
                label: "parentId",
                name: "parentId",
                type: "hide",
                value: node.data.id
            }],
            url: ctxPath + "/admin/orgs",
            method: "PUT",
            contentType: "application/json",
            success: function (data) {
                treeLoader.load();
            }
        });
        form.open();
    }

    function configUpdateButton(node) {
        var form = new layui.LayerForm({
            title: "创建组织",
            onload: {
                url: ctxPath + "/admin/orgs/" + node.data.id
            },
            form: [{
                label: "名称",
                name: "name",
                type: "text"
            }, {
                label: "类型",
                name: "type",
                type: "select",
                options: [{
                    label: "公司",
                    value: 'company'
                }, {
                    label: "部门",
                    value: 'department'
                }, {
                    label: "小组",
                    value: 'team'
                }]
            }, {
                label: "排序",
                name: "ordered",
                type: "text"
            }, {
                label: "parentId",
                name: "parentId",
                type: "hide"
            }, {
                label: "id",
                name: "id",
                type: "hide"
            }],
            url: ctxPath + "/admin/orgs",
            method: "POST",
            contentType: "application/json",
            success: function (data) {
                treeLoader.load();
            }
        });
        form.open();
    }

    function configDeleteButton(node) {
        var dialog = new layui.LayerAjax({
            url: ctxPath + "/admin/orgs/" + node.data.id,
            method: "DELETE",
            success: function (data) {
                treeLoader.load();
                layer.alert("删除成功", {icon: 1})
            }
        })
        dialog.open();
    }
    $("#add_button_id").on('click', function () {
        var node = treeLoader.getSelectedNode()
        if (node == null) {
            layer.msg('请先选择一个组织节点')
            return
        }
        configAddButton(node)
    })
    $("#update_button_id").on('click', function () {
        var node = treeLoader.getSelectedNode()
        if (node == null) {
            layer.msg('请先选择一个组织节点')
            return
        }
        configUpdateButton(node)
    })
    $("#delete_button_id").on('click', function () {
        var node = treeLoader.getSelectedNode()
        if (node == null) {
            layer.msg('请先选择一个组织节点')
            return
        }
        if(node.data.id == 1) {
            layer.msg('禁止删除根节点')
            return
        }
        configDeleteButton(node)
    })

    layui.form.on('submit(search_button_filter)', function (data) {
        var keyword = data.field.keyword
        userTable.reload({
            where : {
                keyword: (keyword || '')
            }
        })
        return false;
    })


})